package com.bear.newsset.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.annotation.Nullable;
import android.widget.Toast;

import com.bear.newsset.util.AppUtil;
import com.bear.newsset.util.LogUtils;
import com.ybear.networkutil.HttpUtil;

import java.io.File;

public class DownloadService extends Service {
    private Context mContext;
    private Message msg;
    private Bundle bundle;
    private String urlPath, savePath;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        init(intent);//初始化
        //请求下载
        HttpUtil.downloadFile(urlPath, savePath, new HttpUtil.CallbackFile() {
            /**
             * 获取请求下载的文件
             * @param file      下载完毕的文件，未完成下载前为null
             * @param process   下载的进度（%）
             * @param result    下载结果（success、failure、processing）三种状态
             */
            @Override
            public void getRequestFile(File file, int process, int result) {
                String text = null;

                //下载成功
                if( result == HttpUtil.RESULT_SUCCESS ) {
                    text = "下载完毕，稍后将进行安装";
                    LogUtils.i("TAG", "PATH:" + file.getAbsolutePath());
                    AppUtil.installApk(mContext, file);
                }
                //下载失败
                if( result == HttpUtil.RESULT_FAILURE ) { text = "下载失败！"; }
                //弹出提示
                if( result != HttpUtil.RESULT_PROCESSING && text != null ) {
                    msg = Message.obtain();
                    bundle = new Bundle();
                    bundle.putString("text", text);
                    msg.setData(bundle);
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
            }
        });
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 初始化
     * @param intent    创建一个意图
     */
    private void init(Intent intent) {
        //下载的地址
        urlPath = intent.getStringExtra("apkUrlPath");
        //保存的地址
        savePath = intent.getStringExtra("savePath");

        msg = Message.obtain();
        bundle = new Bundle();
        bundle.putString("text", "正在下载");
        msg.setData(bundle);
        handler.sendMessage(msg);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 关闭服务后的操作
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.i("TAG", "已关闭下载服务");
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String text = msg.getData().getString("text");
            switch( msg.what ) {
                case 0://关闭服务
                    mContext.stopService(new Intent(mContext, DownloadService.class));
                    break;
            }
            Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
        }
    };
}
